import util from '@/libs/util'
import bus from '@/libs/event-bus'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'

/** 门禁设备详情-门禁类型 */
const accessControlType = {
  2: '公共门',
  3: '单元门'
}

export const generateRoomName = room => room.room_type === 1
  ? room.room_name
  : '公区' + (room.parent_ids.length > 0 ? room.room_name : '')

export const genExceptionsNames = (device, hasNormal) => {
  const {
    online, switch: switchStatus, trans_error, low_amount, longtime_no_open, low_power, device_type
  } = device
  const rules = [{
    name: '离线',
    valid: online === 2
  }, {
    name: '低电',
    deviceType: [2],
    valid: low_power
  }, {
    name: '长时间未开门',
    deviceType: [2],
    valid: longtime_no_open
  }, {
    name: '跳闸',
    deviceType: [3],
    valid: switchStatus === 2
  }, {
    name: '接线异常',
    deviceType: [3, 6, 7],
    valid: online === 2 && trans_error // 设备在线不显示接线异常
  }, {
    name: '欠费',
    deviceType: [3],
    valid: low_amount
  }]

  return renderExceptionsNames(rules, device_type)
}

function renderExceptionsNames (rules, device_type) {
  return rules.reduce((result, option) => {
    if (!option.deviceType || option.deviceType.includes(device_type)) {
      if (option.valid) {
        result.push(option.name)
      }
    }
    return result
  }, [])
}

/**
 * 生成房间设备展示需要的信息,
 * cName 设备展示名称,
 * cTooltipContent 设备tooltip展示内容
 * cIcon 设备展示图标
 * @param {{}[]} 房间设备列表
 * @return {{}[]} 完整的设备信息
 */
export const generateRoomDeviceInfo = (devices, roomType) => devices.map(device => {
  const { device_type, description, ...rest } = device
  const result = { device_type, description, accessControlType: accessControlType[roomType] || '', ...rest }
  const deviceInfo = DeviceTypeEnum.properties[device_type]
  result.cName = description || ((deviceInfo && deviceInfo.name) || '错误设备类型')
  const errors = genExceptionsNames(device)
  const errorMsg = !errors || errors.length === 0 ? '' : errors.join(' / ')
  const iconStatus = errorMsg ? '-offline' : ''
  result.cTooltipContent = errorMsg || null
  if (!deviceInfo) return result
  result.cIcon = deviceInfo.icon + iconStatus
  return result
})

export const generateRoomTenantInfo = leases => {
  if (!leases || leases.length === 0) return ''
  const tenant = leases[0].tenant
  if (!tenant) return '租约异常'
  const name = tenant.name + ' ' + tenant.phone
  return name
}

/**
 * 获取房源房间列表并处理房间和设备信息
 */
export const fetchRoomFromHomeId = async (homeId, params) => {
  const rooms = await http.req(api.room_list, [ homeId ], util.cleanObj(params))
  if (!rooms) return []
  // 将设备图标等信息一次性注入, 房间列表room-card只显示内容
  rooms.forEach(room => {
    room.cRoomName = generateRoomName(room)
    room.cTenantInfo = generateRoomTenantInfo(room.leases)
    if (room.devices.length) {
      room.devices = generateRoomDeviceInfo(room.devices, room.room_type)
    }
  })
  return rooms
}

/**
 * 获取房间详情, 用于更新房间信息
 */
export const fetchRoom = async roomId => {
  const { lease, ...rest } = await http.req(api.room_info, [ roomId ], null)
  const room = { ...rest, leases: [] } // 保持上面的返回结构
  if (lease) room.leases = [ lease ]
  room.cRoomName = generateRoomName(room)
  room.cTenantInfo = generateRoomTenantInfo(room.leases)
  if (room.devices.length) {
    room.devices = generateRoomDeviceInfo(room.devices, room.room_type)
  }
  return room
}

export const refreshRoom = (homeId, roomId, deviceId, newDeviceName) => {
  bus.$emit('refresh-room' + homeId, roomId, deviceId, newDeviceName)
  bus.$emit('refresh-room' + roomId)
}
